package com.kfpanda.search.biz.searchmg;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Service;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.kfpanda.search.biz.BaseBIZ;
import com.kfpanda.search.index.IndexFile;

@Service("indexBIZ")
public class IndexBIZ extends BaseBIZ {
	private Logger logger = Logger.getLogger(IndexBIZ.class);
	@Resource
	private IndexFile indexFiles;
	private String indexPath = "D:\\indexFile";
	private File INDEX_DIR;

	public void indexCreate(String filePath) {
		if (StringUtils.isBlank(filePath)) {
			return;
		}
		if (INDEX_DIR == null) {
			INDEX_DIR = new File(indexPath);
		}
		if (!INDEX_DIR.exists()) {
			logger.setResourceBundle(null);
			logger.error("索引文件保存目录（" + INDEX_DIR + "），无法找到。");
		}

		final File docDir = new File(filePath);
		if (!docDir.exists() || !docDir.canRead()) {
			logger.debug("Document directory '" + docDir.getAbsolutePath()
					+ "' does not exist or is not readable, please check the path");
		}

		Date start = new Date();
		try {
//			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
			Analyzer analyzer = new IKAnalyzer();// 采用的分词器
			//第三个参数 为true表示新建，false表示添加到原有索引中
			IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_DIR),
					analyzer, true,
					IndexWriter.MaxFieldLength.LIMITED);
			logger.debug("Indexing to directory '" + INDEX_DIR + "'...");
			indexFiles.indexDocs(writer, docDir);
			logger.debug("Optimizing...");
			writer.optimize();
			writer.close();

			Date end = new Date();
			logger.debug(end.getTime() - start.getTime() + " total milliseconds");

		} catch (IOException e) {
			logger.error(" caught a " + e.getClass() + "\n with message: ", e);
		}
	}
}
